import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Select,
  Button,
  Table,
  Divider,
  Modal,
} from 'antd';

import { TableListData, TableListParams } from './data';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;

interface SmallWhiteProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: TableListData;
  INITINFO: any;
}

interface SmallWhiteState {
  searchValues: TableListParams;
  statusVisible: boolean;
  delVisible: boolean;
  statusValues: {
    id: number;
    status: number;
  };
  deleteId: number;
  rowId:number;
}

@connect(({
  cooperationCompanySmallWhite: { dataInfo },
  common: { INITINFO },
}: any) => ({
  dataInfo,
  INITINFO,
}))
class SmallWhiteInfoElem extends Component<SmallWhiteProps, SmallWhiteState> {
  columns = [
    { title: '物流中心', dataIndex: 'logisName' },
    { title: '合作账号', dataIndex: 'account' },
    { title: '设备数量', dataIndex: 'deviceNum' },
    { title: '状态', dataIndex: 'statusName' },
    { title: '创建人', dataIndex: 'createUserName' },
    { title: '创建时间', dataIndex: 'createTime' },
    {
      title: '操作',
      render: (cval: any, record: any) => (
        <div>
          <span
            className="operLink"
            onClick={() => this.handleRouter('/basic/cooperationCompany/list/smallWhiteDetail', {
              id: record.id,
            })
            }
          >
            详情
          </span>
          <Divider type="vertical" />
          <span
            className="operLink"
            onClick={() => this.handleChangeStatusModal(true, record)}
          >
            {record.status ? '禁用' : '启用'}
          </span>
          <Divider type="vertical" />
          <span
            className="operLink"
            onClick={() => this.handleRouter('/basic/cooperationCompany/list/smallWhiteEdit', { id: record.id })
            }
          >
            编辑
          </span>
          <Divider type="vertical" />
          <span
            className="operLink"
            onClick={() => this.handleChangeDelModal(true, record)}
          >
            删除
          </span>
        </div>
      ),
    },
  ];

  state: SmallWhiteState = {
    searchValues: {
      logisId: '',
      status: 0,
      pageIndex: 1,
      pageSize: 20,
    },
    statusVisible: false,
    statusValues: {
      id: 0,
      status: 0,
    },
    delVisible: false,
    deleteId: 0,
    rowId: 0,
  };

  componentDidMount() {
    const { searchValues } = this.state;
    this.fetchAction('fetch', searchValues);
    this.fetchAction('common/fetchLogisList');
  }

  handleRouter = (pathname: string, state?: any) => {
    router.push({ pathname, state });
  };

  handleChangeStatusModal = (statusVisible: boolean, record?: any) => {
    this.setState({
      statusVisible,
      statusValues: {
        id: record ? record.id : 0,
        status: record && record.status === 1 ? 0 : 1,
      },
    });
  };

  handleChangeStatus = () => {
    const { statusValues, searchValues: search } = this.state;
    const params = { search, ...statusValues };
    this.fetchAction('changeStatus', params);
    this.handleChangeStatusModal(false);
  };

  handleChangeDelModal = (delVisible: boolean, record?: any) => {
    this.setState({
      delVisible,
      deleteId: record ? record.id : 0,
    });
  };

  handleChangeDel = () => {
    const { deleteId: id, searchValues: search } = this.state;
    const params = { search, id };
    this.fetchAction('changeDelete', params);
    this.handleChangeDelModal(false);
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const { searchValues } = this.state;
      const params = { ...searchValues, ...values };
      this.setState({ searchValues: params }, () => {
        this.fetchAction('fetch', params);
      });
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    this.setState({ searchValues: params }, () => this.fetchAction('fetch', params));
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `cooperationCompanySmallWhite/${typeName}`;
    dispatch({
      type,
      payload,
    });
  };

  render() {
    const {
      searchValues: { pageIndex, pageSize },
      statusVisible,
      delVisible,
      statusValues: { status },
    } = this.state;

    const {
      form: { getFieldDecorator },
      dataInfo,
      INITINFO: { logisList },
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="marginB20">
          <Form
            hideRequiredMark
            className="tableListForm"
            onSubmit={this.handleSearch}
          >
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Form.Item label="物流中心" colon={false}>
                  {getFieldDecorator('logisId')(
                    <Select
                      showSearch
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {logisList.map((item: any) => (
                        <Option value={item.id} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={8} sm={24}>
                <Form.Item label="　　状态" colon={false}>
                  {getFieldDecorator('status', {
                    initialValue: 0,
                  })(
                    <Select placeholder="请选择">
                      <Option value={0}>全部</Option>
                      <Option value={1}>启用</Option>
                      <Option value={2}>禁用</Option>
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={8} sm={24}>
                <div
                  style={{
                    width: '100%',
                    display: 'flex',
                    justifyContent: 'flex-end',
                  }}
                >
                  <Button
                    type="primary"
                    size="small"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false}>
          <Button
            type="primary"
            size="small"
            className="addButton marginB12"
            onClick={() => this.handleRouter('/basic/cooperationCompany/list/smallWhiteAdd')}
          >
            新建
          </Button>
          <Table
            rowKey="id"
            className="statementTable"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <Modal
          title="提示信息"
          visible={statusVisible}
          onOk={this.handleChangeStatus}
          onCancel={() => this.handleChangeStatusModal(false)}
        >
          <p>确定要{status ? '启用' : '禁用'}当前物流中心的小白盒子？</p>
        </Modal>

        <Modal
          title="提示信息"
          visible={delVisible}
          onOk={this.handleChangeDel}
          onCancel={() => this.handleChangeDelModal(false)}
        >
          <p>确定要删除当前物流中心的小白盒子？</p>
        </Modal>

      </Fragment>
    );
  }
}

export default Form.create<SmallWhiteProps>()(SmallWhiteInfoElem);
